package wiki.zimo.certificate_manage.controller;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import wiki.zimo.certificate_manage.constant.Constant;
import wiki.zimo.certificate_manage.dao.*;
import wiki.zimo.certificate_manage.domain.*;
import wiki.zimo.certificate_manage.service.ExcelService;
import wiki.zimo.certificate_manage.service.FileSaveService;
import wiki.zimo.certificate_manage.utils.UUIDUtils;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 *
 * @author 子墨
 * @date 2018/10/23 22:57
 * @describe 处理学生得奖信息
 */
@Controller
@RequestMapping("/studentPrize")
public class StudentPrizeInfoController {

    @Autowired
    private StudentDao studentDao;
    @Autowired
    private StudentPrizeInfoDao prizeInfoDao;
    @Autowired
    private CertificateTypeDao certificateTypeDao;
    @Autowired
    private PrizeNameDao prizeNameDao;
    @Autowired
    private PrizeGradeDao prizeGradeDao;
    @Autowired
    private PrizeLevelDao prizeLevelDao;
    @Autowired
    private ExcelService excelService;
    @Autowired
    private FileSaveService fileSaveService;
    @Value("${file.upload-path}")
    private String uploadPath;

    /**
     * 新增页
     * @author 子墨
     * @date 2018/10/19 10:37
     * @params []
     * @return java.lang.String
     */
    @RequestMapping(value = "add")
    public String add(HttpSession session, Map<String,Object> map){
        User user = (User) session.getAttribute(Constant.USER);
        if (user == null){
            return "redirect:/index";
        }
        String role = user.getRole();
        switch (role){
            case Constant.ROLE_STUDENT:
                map.put("student",user.getStudent());
                break;
            case Constant.ROLE_TEACHER:
                List<Student> students = studentDao.findStudentsByTeacherId(user.getTeacher().getId());
                map.put("students",students);
                break;
            case Constant.ROLE_LEADER:
                List<Student> allStudents = studentDao.findAll();
                map.put("students",allStudents);
                break;
        }
        List<PrizeGrade> prizeGrades = prizeGradeDao.findAll();
        List<PrizeLevel> prizeLevels = prizeLevelDao.findAll();
        List<PrizeName> prizeNames = prizeNameDao.findAll();
        List<CertificateType> certificateTypes = certificateTypeDao.findAll();

        map.put(Constant.USER,user);
        map.put("prizeGrades",prizeGrades);
        map.put("prizeLevels",prizeLevels);
        map.put("prizeNames",prizeNames);
        map.put("certificateTypes",certificateTypes);
        return "studentPrize/add";
    }

    /**
     * 列表页
     * @author 子墨
     * @date 2018/10/19 10:38
     * @params []
     * @return java.lang.String
     */
    @RequestMapping(value = "list")
    public String list(HttpSession session,Map<String,Object> map){
        User user = (User) session.getAttribute(Constant.USER);
        if (user == null){
            return "redirect:/index";
        }
        String role = user.getRole();
        long count = 0;
        switch (role){
            case Constant.ROLE_STUDENT:
                count = prizeInfoDao.countAllByStuId(user.getStudent().getId());
                break;
            case Constant.ROLE_TEACHER:
                count = prizeInfoDao.countAllByTeacherId(user.getTeacher().getId());
                break;
            case Constant.ROLE_LEADER:
                count = prizeInfoDao.count();
        }
        map.put("count",count);
        return "studentPrize/list";
    }

    /**
     * 更新页
     * @author 子墨
     * @date 2018/10/19 15:03
     * @params [map, id]
     * @return java.lang.String
     */
    @RequestMapping(value = "update")
    public String update(HttpSession session,
                         Map<String,Object> map,
                         @RequestParam(value = "id",required = true)String id){
        User user = (User) session.getAttribute(Constant.USER);
        if (user == null){
            return list(session,map);
        }
        String role = user.getRole();
        switch (role){
            case Constant.ROLE_STUDENT:
                return studentDoUpade(id,session,map);
        }
        StudentPrizeInfo prizeInfo = prizeInfoDao.findStudentPrizeInfoById(id);
        map.put("prizeInfo",prizeInfo);
        return add(session,map);
    }

    /**
     * @auther: 子墨
     * @date: 2018/10/29 9:44
     * @describe: 时间线展示学生获奖信息
     * @param: [map, id]
     * @return: java.lang.String
     * @version v1.0
     */
    @RequestMapping(value = "/timeline")
    public String timeline(Map<String,Object> map,
                           @RequestParam(value = "id",required = false)String id){
        StudentPrizeInfo info = prizeInfoDao.findStudentPrizeInfoById(id);
        List<StudentPrizeInfo> prizeInfos = prizeInfoDao.findAllByStuId(info.getStuId());
        map.put("prizeInfos",prizeInfos);
        return "studentPrize/timeline";
    }

    /**
     * 一键导出Excel数据
     * @author 子墨
     * @date 2018/10/19 15:09
     * @params [response]
     * @return void
     */
    @RequestMapping(value = "/export")
    public void exportExcel(HttpServletResponse response,HttpSession session) {
        User user = (User) session.getAttribute(Constant.USER);
        List<StudentPrizeInfo> list = new ArrayList<>();
        if (user == null){
            return;
        }
        String role = user.getRole();
        switch (role){
            case Constant.ROLE_STUDENT:
                list = prizeInfoDao.findAllByStuId(user.getStudent().getId());
                break;
            case Constant.ROLE_TEACHER:
                list = prizeInfoDao.findAllByTeacherId(user.getTeacher().getId());
                break;
            case Constant.ROLE_LEADER:
                list = prizeInfoDao.findAll();
        }
        for (StudentPrizeInfo info:list){
            info.setPrizePhoto(uploadPath+info.getPrizePhoto());
        }
        System.out.println(list.toString());
        // 指定列表标题和工作表名称
        ExportParams params = new ExportParams("学生获奖信息信息","学生获奖信息信息表");
        try {
            excelService.doExportExcel(response,list,StudentPrizeInfo.class,params,"学生获奖信息信息表");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    /**
     * 新增或者修改学生获奖信息信息接口
     * @author 子墨
     * @date 2018/10/18 22:53
     * @params [map, id, schoolName]
     * @return wiki.zimo.certificate_manage.domain.Student
     */
    @Transactional
    @RequestMapping(value = "/addStudentPrizeInfo")
    @ResponseBody
    public StudentPrizeInfo addStudentPrizeInfo(Map<String,Object> map,
                                                @RequestParam(value = "id",required = false)String id,
                                                @RequestParam(value = "studentId",required = true)String studentId,
                                                @RequestParam(value = "certificateType",required = true)String certificateType,
                                                @RequestParam(value = "leadTeacher",required = true) String leadTeacher,
                                                @RequestParam(value = "prizeTime",required = false) @DateTimeFormat(pattern = "yyyy-MM") Date prizeTime,
                                                @RequestParam(value = "prizeName",required = true) String prizeName,
                                                @RequestParam(value = "prizeGrade",required = true) String prizeGrade,
                                                @RequestParam(value = "prizeLevel",required = true) String prizeLevel,
                                                @RequestParam(value = "prizeDetails",required = false) String prizeDetails,
                                                @RequestParam(value = "file",required = true)MultipartFile file){
        if (id == null || id.replaceAll(" ","").equals("")){
            Student student = studentDao.findStudentById(studentId);
            StudentPrizeInfo info = new StudentPrizeInfo();
            info.setId(UUIDUtils.getRandomID());
            info.setStuId(student.getId());
            info.setTeacherId(student.getTeacherId());
            info.setStuName(student.getStuName());
            info.setStuClass(student.getStuClass());
            info.setStuMajor(student.getStuMajor());
            info.setStuSchool(student.getStuSchool());
            info.setCertificateType(certificateType);
            info.setLeadTeacher(leadTeacher);
            info.setPrizeTime(new Timestamp(prizeTime.getTime()));
            info.setPrizeName(prizeName);
            info.setPrizeGrade(prizeGrade);
            info.setPrizeLevel(prizeLevel);
            info.setPrizeDetails(prizeDetails);
            info.setReportTime(new Timestamp(System.currentTimeMillis()));
            info.setAuditingStatus(Constant.UNAUDITED);
            info.setPrizePhoto(fileSaveService.savaFile(file));
            return prizeInfoDao.save(info);
        }
        Student student = studentDao.findStudentById(studentId);
        StudentPrizeInfo info = prizeInfoDao.findStudentPrizeInfoById(id);
        info.setStuId(student.getId());
        info.setTeacherId(student.getTeacherId());
        info.setStuName(student.getStuName());
        info.setStuClass(student.getStuClass());
        info.setStuMajor(student.getStuMajor());
        info.setStuSchool(student.getStuSchool());
        info.setCertificateType(certificateType);
        info.setLeadTeacher(leadTeacher);
        info.setPrizeTime(new Timestamp(prizeTime.getTime()));
        info.setPrizeName(prizeName);
        info.setPrizeGrade(prizeGrade);
        info.setPrizeLevel(prizeLevel);
        info.setPrizeDetails(prizeDetails);
        info.setReportTime(new Timestamp(System.currentTimeMillis()));
        info.setAuditingStatus(Constant.UNAUDITED);
        info.setPrizePhoto(fileSaveService.savaFile(file));
        return prizeInfoDao.save(info);

    }

    /**
     * 得到所有学生获奖信息信息接口
     * @author 子墨
     * @date 2018/10/19 12:38
     * @params []
     * @return java.util.List<wiki.zimo.certificate_manage.domain.Student>
     */
    @RequestMapping(value = "/getAllStudentPrizeInfo")
    @ResponseBody
    public List<StudentPrizeInfo> getAllStudentPrizeInfo(HttpSession session){
        User user = (User) session.getAttribute(Constant.USER);
        String role = user.getRole();
        if (role == null){
            return null;
        }
        switch (role){
            case Constant.ROLE_STUDENT:
                return prizeInfoDao.findAllByStuId(user.getStudent().getId());
            case Constant.ROLE_TEACHER:
                return prizeInfoDao.findAllByTeacherId(user.getTeacher().getId());
        }
        return prizeInfoDao.findAll();
    }

    /**
     * 删除学生获奖信息信息接口
     * @author 子墨
     * @date 2018/10/19 14:11
     * @params [id]
     * @return java.lang.String
     */
    @RequestMapping(value = "delete")
    public String delete(Map<String,Object> map,
                         HttpSession session,
                         @RequestParam(value = "id")String id){
        User user = (User) session.getAttribute(Constant.USER);
        if (user == null){
            return list(session,map);
        }
        String role = user.getRole();
        switch (role){
            case Constant.ROLE_STUDENT:
                studentDoDelete(id,map);
                return list(session,map);
        }
        if (prizeInfoDao.existsById(id)){
            prizeInfoDao.deleteById(id);
            map.put(Constant.MSG,"提示：删除成功");
        }
        return list(session,map);
    }

    /**
     * @auther: 子墨
     * @date: 2018/10/28 21:54
     * @describe: 获奖信息修改审核状态接口
     * @param: [id]
     * @return: java.lang.String
     * @version v1.0
     */
    @RequestMapping(value = "audite")
    public String audite(HttpSession session,
                              Map<String,Object> map,
                              @RequestParam(value = "id")String id){
        User user = (User) session.getAttribute(Constant.USER);
        if (user == null){
            return list(session,map);
        }
        String role = user.getRole();
        switch (role){
            case Constant.ROLE_STUDENT:
                return list(session,map);
            case Constant.ROLE_TEACHER:
                teacherDoAudite(id,map,user.getTeacher());
                return list(session,map);
            case Constant.ROLE_LEADER:
                leaderDoAudite(id,map,user.getLeader());
                return list(session,map);
        }
        return list(session,map);
    }

    /**
     * @auther: 子墨
     * @date: 2018/10/29 8:48
     * @describe: 分管领导审核
     * @param: [id, map, leader]
     * @return: void
     * @version v1.0
     */
    private void leaderDoAudite(String id, Map<String,Object> map, Leader leader) {
        StudentPrizeInfo info = prizeInfoDao.findStudentPrizeInfoById(id);
        if ( ! info.getAuditingStatus().equals(Constant.AUDITED)){
            info.setAuditingStatus(Constant.AUDITED);
            info.setAuditingPeople(leader.getTeacherName());
            info.setAuditingTime(new Timestamp(System.currentTimeMillis()));
            map.put(Constant.MSG,"操作成功，当前审核状态为——"+Constant.AUDITED);
        }else {
            info.setAuditingStatus(Constant.REJECT);
            map.put(Constant.MSG,"操作成功，当前审核状态为——"+Constant.REJECT);
        }
        prizeInfoDao.save(info);
    }

    /**
     * @auther: 子墨
     * @date: 2018/10/29 8:45
     * @describe: 教师审核通过
     * @param: [id, teacher]
     * @return: void
     * @version v1.0
     */
    private void teacherDoAudite(String id, Map<String,Object> map, Teacher teacher) {
        StudentPrizeInfo info = prizeInfoDao.findStudentPrizeInfoById(id);
        if ( ! info.getAuditingStatus().equals(Constant.AUDITED)){
            info.setAuditingStatus(Constant.AUDITED);
            info.setAuditingPeople(teacher.getTeacherName());
            info.setAuditingTime(new Timestamp(System.currentTimeMillis()));
            map.put(Constant.MSG,"操作成功，当前审核状态为——"+Constant.AUDITED);
        }else {
            info.setAuditingStatus(Constant.REJECT);
            map.put(Constant.MSG,"操作成功，当前审核状态为——"+Constant.REJECT);
        }
        prizeInfoDao.save(info);
    }

    /**
     * @auther: 子墨
     * @date: 2018/10/28 21:37
     * @describe: 学生删除获奖信息
     * @param: [id, map]
     * @return: void
     * @version v1.0
     */
    private void studentDoDelete(String id, Map<String,Object> map) {
        StudentPrizeInfo info = prizeInfoDao.findStudentPrizeInfoById(id);
        if (info.getAuditingStatus().equals(Constant.AUDITED)){
            map.put(Constant.MSG,"提示，当前状态没有权限删除");
        }else {
            if (prizeInfoDao.existsById(id)){
                prizeInfoDao.deleteById(id);
                map.put(Constant.MSG,"提示：删除成功");
            }
        }
    }
    
    /**
     * @auther: 子墨
     * @date: 2018/10/29 9:05
     * @describe: 学生修改获奖信息
     * @param: [id, session, map]
     * @return: java.lang.String
     * @version v1.0
     */
    private String studentDoUpade(String id, HttpSession session, Map<String,Object> map){
        StudentPrizeInfo prizeInfo = prizeInfoDao.findStudentPrizeInfoById(id);
        System.out.println(prizeInfo.getAuditingStatus());
        if (prizeInfo.getAuditingStatus().equals(Constant.AUDITED)){
            map.put(Constant.MSG,"提示，当前状态没有权限修改");
            return list(session,map);
        }else {
            map.put("prizeInfo",prizeInfo);
            return add(session,map);
        }
    }
}
